package com.yuyou.fn.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.springframework.util.StringUtils;

/**
 * Created by Administrator on 2018/5/29.
 */
public class Util {
    public static final String EMPTY = "";

    public static List<Long> toLongIds(String idsStr) {

        if (StringUtils.isEmpty(idsStr)) {
            return Collections.EMPTY_LIST;
        }

        String[] idsArr = idsStr.split(",");
        if (idsArr.length == 0) {
            return Collections.emptyList();
        }
        List<Long> ids = new ArrayList<>();
        for (String c : idsArr) {
            ids.add(Long.valueOf(c.trim()));
        }
        return ids;
    }

    public static List<String> toStrings(String idsStr) {

        if (StringUtils.isEmpty(idsStr)) {
            return Collections.EMPTY_LIST;
        }

        String[] idsArr = idsStr.split(",");
        if (idsArr.length == 0) {
            return Collections.emptyList();
        }
        List<String> ids = new ArrayList<>();
        for (String c : idsArr) {
            ids.add(c.trim());
        }
        return ids;
    }


    public static String join(final Iterable<?> iterable, final String separator) {
        if (iterable == null) {
            return null;
        }
        return join(iterable.iterator(), separator);
    }

    public static String join(final Iterator<?> iterator, final String separator) {

        // handle null, zero and one elements before building a buffer
        if (iterator == null) {
            return null;
        }
        if (!iterator.hasNext()) {
            return EMPTY;
        }
        final Object first = iterator.next();
        if (!iterator.hasNext()) {
            @SuppressWarnings( "deprecation" ) // ObjectUtils.toString(Object) has been deprecated in 3.2
            final String result = Util.toString(first);
            return result;
        }

        // two or more elements
        final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
        if (first != null) {
            buf.append(first);
        }

        while (iterator.hasNext()) {
            if (separator != null) {
                buf.append(separator);
            }
            final Object obj = iterator.next();
            if (obj != null) {
                buf.append(obj);
            }
        }
        return buf.toString();
    }

    public static String toString(final Object obj) {
        return obj == null ? "" : obj.toString();
    }

}
